04. 解决方案: For 循环
解决方案: 列表的总和
def list_sum(input_list):
sum = 0
for element in input_list:
sum += element
return sum
#These test cases check that list_sum works correctly
test1 = list_sum([1, 2, 3])
print("expected result: 6, actual result: {}".format(test1))
test2 = list_sum([-1, 0, 1])
print("expected result: 0, actual result: {}".format(test2))
format
函数的说明可以参考
这里
。
解决方案: XML 标签计数器
def tag_count(list1):
count = 0
for element in list1:
if element[0] == '<' and element[-1] == '>':
count += 1
return count
# Test for the tag_count function:
list1 = ['<greeting>', 'Hello World!', '</greeting>']
count = tag_count(list1)
print("Expected result: 2, Actual result: {}".format(count))
解决方案:创建 HTML 列表
def html_list(list_items):
HTML_string = "<ul>\n"
for item in list_items:
HTML_string += "<li>{}</li>\n".format(item)
HTML_string += "</ul>"
return HTML_string
print(html_list(['First element', 'Second element', 'Third element']))
解决方案: Starbox
我们可以通过下面的训话来打印正确的行数:
for _ in range(height-2):
print("*" + " " * (width-2) + "*")
这个循环使用
range
作为一个简单的计数器,循环的主体部分执行了
height - 2
次。下划线
_
是一个无关变量,因为我们在循环计数中对它的实际值并不感兴趣。
下面是完整解决方案:
def starbox(width, height):
"""print a box made up of asterisks.
width: width of box in characters, must be at least 2
height: height of box in lines, must be at least 2
"""
print("*" * width) #print top edge of box
# print sides of box
for _ in range(height-2):
print("*" + " " * (width-2) + "*")
print("*" * width) #print bottom edge of box